public class Leetcode1781 {
    public static void main(String[] args) {
        System.out.println(beautySum("aabcb"));
        System.out.println(beautySum("aabcbaa"));
    }

    public static int beautySum(String s) {
        char[] sChars = s.toCharArray();
        int res = 0;
        int[] count;
        for (int i = 0; i < sChars.length; ++i) {
            count = new int[26];
            for (int j = i; j < sChars.length; ++j) {
                ++count[sChars[j] - 'a'];
                int max = Integer.MIN_VALUE;
                int min = Integer.MAX_VALUE;
                for (int c : count) {
                    if (c == 0) {
                        continue;
                    }

                    if (c > max) {
                        max = c;
                    }

                    if (c < min) {
                        min = c;
                    }
                }

                if (max != min && min != Integer.MAX_VALUE) {
                    res += max - min;
                }

            }

        }

        return res;
    }

}
